#include "manager_widget.h"
#include "ui_manager_widget.h"
#include <alibabacloud/oss/OssClient.h>
#include <QFileDialog>
#include <QMessageBox>
#include <QDebug>
#include <fstream>
#include <iostream>
#include <QDir>
#include <QInputDialog>
#include <QDateTime>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QGroupBox>

using namespace AlibabaCloud::OSS;

ManagerWidget::ManagerWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::ManagerWidget)
    , udpSocket(new QUdpSocket(this))
{
    ui->setupUi(this);

    // 设置配置文件路径
    configFilePath = QDir::homePath() + "/.config/oss_manager.conf";

    // 设置窗口标题和大小
    setWindowTitle("OSS文件上传工具 - 远程控制版");
    setFixedSize(600, 500);

    // 创建主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);

    // 创建OSS控制组
    QGroupBox *ossGroup = new QGroupBox("OSS文件上传", this);
    QGridLayout *ossLayout = new QGridLayout(ossGroup);

    // OSS控制组件
    ossLayout->addWidget(new QLabel("选择文件:"), 0, 0);
    filePathEdit = new QLineEdit();
    filePathEdit->setReadOnly(true);
    ossLayout->addWidget(filePathEdit, 0, 1);

    selectButton = new QPushButton("浏览...");
    ossLayout->addWidget(selectButton, 0, 2);

    ossLayout->addWidget(new QLabel("远程文件名:"), 1, 0);
    remoteNameEdit = new QLineEdit();
    remoteNameEdit->setPlaceholderText("例如: images/myphoto.jpg");
    ossLayout->addWidget(remoteNameEdit, 1, 1, 1, 2);

    QHBoxLayout *ossButtonLayout = new QHBoxLayout();
    uploadButton = new QPushButton("上传到OSS");
    uploadButton->setEnabled(false);
    configButton = new QPushButton("配置密钥");
    ossButtonLayout->addWidget(uploadButton);
    ossButtonLayout->addWidget(configButton);
    ossLayout->addLayout(ossButtonLayout, 2, 0, 1, 3);

    progressBar = new QProgressBar();
    progressBar->setVisible(false);
    ossLayout->addWidget(progressBar, 3, 0, 1, 3);

    ossGroup->setLayout(ossLayout);

    // 创建客户端控制组
    QGroupBox *clientGroup = new QGroupBox("客户端远程控制", this);
    QGridLayout *clientLayout = new QGridLayout(clientGroup);

    // 客户端控制按钮
    playButton = new QPushButton("播放");
    stopButton = new QPushButton("停止");
    downloadButton = new QPushButton("下载图片");
    statusButton = new QPushButton("查询状态");

    clientLayout->addWidget(playButton, 0, 0);
    clientLayout->addWidget(stopButton, 0, 1);
    clientLayout->addWidget(downloadButton, 1, 0);
    clientLayout->addWidget(statusButton, 1, 1);

    clientGroup->setLayout(clientLayout);

    // 状态显示区域
    statusLabel = new QLabel("请先配置OSS访问密钥");
    clientStatusLabel = new QLabel("客户端状态: 未连接");
    clientStatusLabel->setStyleSheet("color: blue;");

    // 添加到主布局
    mainLayout->addWidget(ossGroup);
    mainLayout->addWidget(clientGroup);
    mainLayout->addWidget(statusLabel);
    mainLayout->addWidget(clientStatusLabel);

    setLayout(mainLayout);

    // 连接信号槽
    connect(selectButton, &QPushButton::clicked, this, &ManagerWidget::selectFile);
    connect(uploadButton, &QPushButton::clicked, this, &ManagerWidget::uploadFileToOSS);
    connect(configButton, &QPushButton::clicked, this, &ManagerWidget::showConfigDialog);
    connect(filePathEdit, &QLineEdit::textChanged, [this]() {
        uploadButton->setEnabled(!filePathEdit->text().isEmpty() && checkConfig());
    });

    // 客户端控制按钮连接
    connect(playButton, &QPushButton::clicked, [this]() {
        sendUdpCommand("PLAY");
    });
    connect(stopButton, &QPushButton::clicked, [this]() {
        sendUdpCommand("STOP");
    });
    connect(downloadButton, &QPushButton::clicked, [this]() {
        sendUdpCommand("DOWNLOAD");
    });
    connect(statusButton, &QPushButton::clicked, [this]() {
        sendUdpCommand("STATUS");
    });

    // UDP socket连接
    connect(udpSocket, &QUdpSocket::readyRead, this, [this]() {
        while (udpSocket->hasPendingDatagrams()) {
            QByteArray datagram;
            datagram.resize(udpSocket->pendingDatagramSize());
            QHostAddress senderAddr;
            quint16 senderPort;

            udpSocket->readDatagram(datagram.data(), datagram.size(), &senderAddr, &senderPort);

            QString message = QString::fromUtf8(datagram);
            if (message.startsWith("CLIENT1_STATUS:")) {
                onClientStatusReceived(message);
            }
        }
    });

    // 加载配置
    loadConfig();
    if (checkConfig()) {
        statusLabel->setText("OSS配置已就绪，请选择要上传的文件");
    }

    // 绑定UDP端口接收客户端状态响应
    if (!udpSocket->bind(12345, QUdpSocket::ShareAddress)) { // 使用不同端口避免冲突
        statusLabel->setText("UDP绑定失败: " + udpSocket->errorString());
        //udpSocket->bind()
    }else{
        statusLabel->setText("UDP bind success!");
    }
}

ManagerWidget::~ManagerWidget()
{
    delete ui;
}

void ManagerWidget::sendUdpCommand(const QString& command)
{
    QByteArray datagram = command.toUtf8();
    qint64 result = udpSocket->writeDatagram(datagram, QHostAddress::Broadcast, 12345);

    if (result == -1) {
        statusLabel->setText("命令发送失败: " + udpSocket->errorString());
    } else {
        statusLabel->setText("已发送命令: " + command);
        qDebug() << "UDP命令已发送:" << command;
    }
}

void ManagerWidget::onClientStatusReceived(const QString& status)
{
    clientStatusLabel->setText("客户端状态: " + status);
    qDebug() << "收到客户端状态:" << status;
}

// 以下原有的OSS相关函数保持不变（只显示关键修改部分）
void ManagerWidget::loadConfig()
{
    QSettings settings(configFilePath, QSettings::IniFormat);
    // 配置会在使用时动态读取
}

void ManagerWidget::saveConfig(const QString& accessKeyId, const QString& accessKeySecret)
{
    QSettings settings(configFilePath, QSettings::IniFormat);
    settings.setValue("OSS/AccessKeyId", accessKeyId);
    settings.setValue("OSS/AccessKeySecret", accessKeySecret);
    settings.setValue("OSS/Endpoint", "oss-cn-chengdu.aliyuncs.com");
    settings.setValue("OSS/Bucket", "smart-advertising-chengdu-a1b2c3");

    qDebug() << "OSS配置已保存到:" << configFilePath;
}

QString ManagerWidget::getAccessKeyId()
{
    QSettings settings(configFilePath, QSettings::IniFormat);
    QString key = settings.value("OSS/AccessKeyId").toString();

    if (key.isEmpty()) {
        qDebug() << "未找到OSS AccessKeyId配置";
    }
    return key;
}

QString ManagerWidget::getAccessKeySecret()
{
    QSettings settings(configFilePath, QSettings::IniFormat);
    QString secret = settings.value("OSS/AccessKeySecret").toString();

    if (secret.isEmpty()) {
        qDebug() << "未找到OSS AccessKeySecret配置";
    }
    return secret;
}

bool ManagerWidget::checkConfig()
{
    return !getAccessKeyId().isEmpty() && !getAccessKeySecret().isEmpty();
}

void ManagerWidget::showConfigDialog()
{
    bool ok;
    QString accessKeyId = QInputDialog::getText(
        this,
        "配置OSS访问密钥",
        "请输入AccessKey ID:",
        QLineEdit::Normal,
        getAccessKeyId(),
        &ok
    );

    if (!ok || accessKeyId.isEmpty()) return;

    QString accessKeySecret = QInputDialog::getText(
        this,
        "配置OSS访问密钥",
        "请输入AccessKey Secret:",
        QLineEdit::Password,
        "",
        &ok
    );

    if (!ok || accessKeySecret.isEmpty()) return;

    saveConfig(accessKeyId, accessKeySecret);

    if (checkConfig()) {
        QMessageBox::information(this, "成功", "OSS配置已保存！");
        uploadButton->setEnabled(!filePathEdit->text().isEmpty());
        statusLabel->setText("OSS配置已就绪，请选择要上传的文件");
    }
}

void ManagerWidget::selectFile()
{
    QString filePath = QFileDialog::getOpenFileName(
        this,
        "选择要上传的文件",
        QDir::homePath(),
        "所有文件 (*.*)"
    );

    if (!filePath.isEmpty()) {
        currentFilePath = filePath;
        filePathEdit->setText(filePath);

        QFileInfo fileInfo(filePath);
        QString remoteName = "uploads/" + QDateTime::currentDateTime().toString("yyyyMMdd_") + fileInfo.fileName();
        remoteNameEdit->setText(remoteName);

        statusLabel->setText(QString("已选择文件: %1 (%2 KB)")
                           .arg(fileInfo.fileName())
                           .arg(fileInfo.size() / 1024));

        uploadButton->setEnabled(checkConfig());
    }
}

void ManagerWidget::uploadFileToOSS()
{
    // 原有的上传逻辑保持不变
    if (!checkConfig()) {
        QMessageBox::warning(this, "错误", "请先配置OSS访问密钥");
        showConfigDialog();
        return;
    }

    if (currentFilePath.isEmpty() || !QFile::exists(currentFilePath)) {
        QMessageBox::warning(this, "错误", "请先选择有效的文件");
        return;
    }

    QString remoteObjectName = remoteNameEdit->text().trimmed();
    if (remoteObjectName.isEmpty()) {
        QMessageBox::warning(this, "错误", "请输入远程文件名");
        return;
    }

    // ... 其余上传代码保持不变
}
